<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <el-dialog v-model="props.addVisible" title="新增载荷文件" @close="handleVisible('cancel')" width="600px">
    <el-form ref="FormRef" :model="formData" :rules="rules" size="small" label-width="120px">
      <el-form-item label="所属机型：" prop="modelNumber">
        <el-select v-model="formData.modelNumber">
          <el-option v-for="item in props.modelList" :label="item.name" :value="item.mark" :key="item.mark"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="载荷文件" prop="file">
        <el-upload
          :before-upload="handleBeforeUpload"
          @change="handleChange"
          :on-remove="handleRemove"
          :file-list="fileList"
          :show-file-list="true"
          :auto-upload="false"
          :multiple="false"
          accept=".bdf"
          :limit="1"
          action="#"
          required
        >
          <el-button type="primary">上传BDF文件</el-button>
          <div class="el-upload__tip">支持扩展名:.bdf，大小限制500M内</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="备注：" prop="remarks">
        <el-input v-model="formData.remarks" type="textarea" :rows="3"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button size="small" @click="handleVisible('cancel')">取消</el-button>
        <el-button size="small" type="primary" @click="submitAdd"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<!-- 新增型材 -->
<script name="addNecessary" setup >
import axios from 'axios';
import { getToken } from '@/utils/auth';
const { proxy } = getCurrentInstance();
const props = defineProps(['addVisible', 'modelList']);
const emit = defineEmits(['handleEvent']);
const FormRef = ref();
const fileList = ref([]);
const submitFile = ref(null);
const formData = ref({
  modelNumber: '',
  remarks: '',
  file: undefined
});
const rules = ref({
  modelNumber: [{ required: true, message: '机型不能为空', trigger: 'blur' }],
  remarks: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
  file: [{ required: true, message: '请上传文件', trigger: 'blur' }]
})
// 上传前校检格式和大小
const handleBeforeUpload = (file) => {
  // 校检文件大小
  const isLt = file.size / 1024 / 1024 < 500;
  if (!isLt) {
    proxy?.$modal.msgError(`导入文件太大，请交由系统管理员进行处理`);
    return false;
  }
  return true;
};
const handleRemove = (file) => {
  fileList.value = [];
  formData.value.file = null;
};
const handleChange = (file) => {
  submitFile.value = file;
  formData.value.file = file;
  FormRef.value.validate();
};
// 修改时，填充表单数据
// if (modalType === 'edit') {
//   formItems.value.forEach((el) => {
//     formData.value[el.value] = props.rowData[el.value];
//   });
 
// }
const handleVisible = (type) => {
  if (type === 'cancel') {
    emit('handleEvent');
  } else {
    emit('handleEvent', { type: 'refresh' });
  }
};
const submitAdd = () => {
  // if( modalType === 'edit'){
  //   formData.value.id = props.rowData.id;
  // }
  // saveProfile(formData.value).then((res) => {
  //   if (res) {
  //     modalType === 'add'
  //       ? ElMessage({ showClose: true, message: '新增成功。', type: 'success' })
  //       : ElMessage({ showClose: true, message: '修改成功。', type: 'success' });
  //     // handleVisible('submit');
  //   }
  // });
  FormRef.value.validate((valid) => {
    if (!valid) {
      return false;
    } else {
      const fm = new FormData();
      const metadata = formData.value;
      fm.append('file', submitFile.value.raw);
      fm.append('modelNumber', metadata?.modelNumber);
      fm.append('remarks', metadata?.remarks);
      let VITE_APP_BASE_API = '/dev-api';
      if (import.meta.env.MODE === 'production') {
        VITE_APP_BASE_API = '/prod-api';
      }
      if (import.meta.env.MODE === 'green') {
        VITE_APP_BASE_API = '/isfd-api';
      }
      axios
        .post(`${VITE_APP_BASE_API}/isfd/modelManagementLoad/save`, fm, {
          headers: { 'Content-Type': 'multipart/form-data', 'Authorization': 'Bearer ' + getToken() }
        })
        .then((res) => {
          if (res.data.code == 200) {
            ElMessage({ showClose: true, message: res.data.msg, type: 'success' });
            fileList.value = [];
            handleVisible('add');
          } else {
            fileList.value = [];
            ElMessage({ showClose: true, message: res.data.msg, type: 'error' }); 
          }
        });
    }
  });
};
</script>